//
//  GHTextField.m
//  LGHKitDemo
//
//  Created by yolanda on 2025/6/27.
//

#import "GHTextField.h"

@interface GHTextField ()<UITextFieldDelegate>

@end

@implementation GHTextField

- (instancetype)init {
    self = [super init];
    if(self) {
        self.delegate =  self;
    }
    return self;
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidChangeSelection:(UITextField *)textField {
    UITextRange *markedRange = [textField markedTextRange];
    NSString * newString = [textField textInRange:markedRange];
    if(newString.length==0 && (self.lengthLimit > 0)){
        // 不能超过self.lengthLimit的长度
        if(textField.text.length >= self.lengthLimit){
            textField.text = [textField.text substringWithRange:NSMakeRange(0, self.lengthLimit)];
        }
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // 只能输入数字
    if(self.numberLimit){
        NSString *format = @"0123456789";
        NSCharacterSet* filterCS = [[NSCharacterSet characterSetWithCharactersInString:format] invertedSet];
        NSString *filterString = [[string componentsSeparatedByCharactersInSet:filterCS] componentsJoinedByString:@""];
        // 只能输入数字
        if(![string isEqualToString:filterString]) {
            return NO;
        }
        
        // maxNumber
        NSString *nextString = [textField.text  stringByReplacingCharactersInRange:range withString:string];
        if(self.maxinumValue>0) {
            if(nextString.integerValue > self.maxinumValue) {
                return NO;
            }
        }
        
        // zeroLimit 限制输入00 000 0000 00000 ...
        if(self.zeroLimit) {
            if([textField.text isEqualToString:@"0"] && ([string isEqualToString:@"0"])){
                // 限制输入00，000,0000,00000
                return NO;
            }
        }
    }
    
    // 只能允许输入数字
    if(self.characterLimit){
        NSString *format = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        NSCharacterSet* filterCS = [[NSCharacterSet characterSetWithCharactersInString:format] invertedSet];
        NSString *filterString = [[string componentsSeparatedByCharactersInSet:filterCS] componentsJoinedByString:@""];
        
        if(![string isEqualToString:filterString]) {
            return NO;
        }
    }
    
    // NoneSpaceLimit  //没有空格的限制
    if(self.spaceLimit) {
        // 不能输入空格
        if([string isEqualToString:@" "] && (string.length==1)) {
            return NO;
        }
    }
    return YES;
}

@end
